<?php

namespace Admin\Controller;
use Think\Controller;

class MessagesController extends BaseController{

	/**
	 * 管理友情链接
	 */
	public function index(){
		$page=I('get.p')?I('get.p'):1;
        $pageSize=10;
        $amessageCount=M("messages")->where('`to`=0')->count();
        $Page=new \Think\Page($amessageCount,$pageSize);
        $messages=M('messages')->where('is_admin=0')->order('id desc')->limit(($page-1)*$pageSize,$pageSize)->select();
        foreach ($messages as $key => $message) {
            if($message['to']!=0){
                $messages[$key]['replay']=M('messages')->field('nickname')->find($message['to'])['nickname'];
            }
        }
        $Page->setConfig('header', '共<b> %TOTAL_ROW% </b>条记录，当前第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页');
        $Page->setConfig("prev","上一页");
        $Page->setConfig("next","下一页");
        $Page->setConfig('theme', '<ul class="am-pagination"><li>%UP_PAGE%</li>%LINK_PAGE%<li>%DOWN_PAGE%</li><li>%HEADER%</li></ul>');
        $this->pager=$Page->show();
		$this->messages=$messages;
		$this->title='网站留言管理';
		$this->display();
	}

	/**
	 * 删除留言
	 */
	public function deleteMsg(){
		if(IS_AJAX){
			$sub=M('messages')->where('`to`='.I('post.id'))->find();
			if(!empty($sub)){
				//连同回复一块删除
				M('messages')->where('`to`='.I('post.id'))->delete();
			}
			if(M('messages')->delete(I('post.id'))){
                $this->ajaxReturn(array('status'=>1,'msg'=>'删除完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
            }    
		}else{
			$this->error('访问错误');
		}
	}

	/**
	 * 回复留言
	 */
	public function replay(){
        if(IS_AJAX){
        	$data=array('to'=>I('post.id'),'message'=>I('post.message'));
        	$data['create_time']=time();
        	$data['browser']=getBrowser();
            $data['systemOS']=getOs();
			$data['is_admin']=1;
			$data['nickname']=session('userinfo')[0]['username'];
            if(M('messages')->add($data)){
                if(F('webSet')['Semail']==1){
                    /*发邮件通知*/
                    $toEmail=M('messages')->field('email')->find(I('post.id'))['email'];
                    if(!empty($toEmail)){
                        $msg=F('webSet')['webtitle']."的站长回复了你的留言:<p>{$data['message']}</p><br><a href='".U('/index/messagewall'.'@'.$_SERVER['SERVER_NAME'])."'>点击查看</a>";
                        $res=sendMail($toEmail,F('webSet')['webtitle'].'|系统回复',$msg);
                        if($res!==true){
                            $this->ajaxReturn(array('status'=>1,'msg'=>'回复完成，但是邮件发送失败：'.$res));
                        }
                    }
                }
            	$this->ajaxReturn(array('status'=>1,'msg'=>'回复完成'));
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'回复失败'));
            }
        }else{
        	$this->error('访问错误');
        }
	}

}